//
//  ViewController8.swift
//  Animation
//
//  Created by 左忠飞 on 2021/1/14.
//  Copyright © 2021 左忠飞. All rights reserved.
//

import UIKit

class ViewController8: UIViewController, UITextViewDelegate {

    var textView:UITextView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
        let view = UIView()
        view.backgroundColor = .orange
        self.view.addSubview(view)
        view.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(120)
            make.bottom.equalTo(-20)
        }
        
        //使用自动布局技术,让文本输入框随着文字输入变高,但是有最高限制,文字删除后,文本输入框高度慢慢变小
        textView = UITextView()
        textView?.layer.borderWidth = 1
        textView?.layer.borderColor = UIColor.gray.cgColor
        textView?.delegate = self
        self.view .addSubview(textView!)
        textView?.snp.makeConstraints({ (make) in
            make.leading.equalTo((100))
            make.trailing.equalTo((-100))
            make.top.equalTo((200))
            make.height.equalTo(30)
        })
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if textView.contentSize.height != textView.bounds.size.height && textView.bounds.size.height < 100 {
            textView.snp.updateConstraints { (make) in
                make.height.equalTo(textView.contentSize.height)
            }
            //自动布局过程中,添加动画,只要把self.view.layoutIfNeeded()方法调用放在动画执行block中就可以了
            UIView.animate(withDuration: 0.3) {
                self.view.layoutIfNeeded()
            }
        }
        
        if textView.bounds.size.height >= 100 {
            if textView.contentSize.height < textView.bounds.size.height {
                textView.snp.updateConstraints { (make) in
                    make.height.equalTo(textView.contentSize.height)
                }
            }
        }
        return true
    }

}
